import {
	baseUrl,
	setCookie,
	getCookie,
	removeCookie
} from "./config";

export function topList() {
	return new Promise(function(resolve, reject) {
		uni.request({
			url: `${baseUrl}/toplist/detail`,
			method: "GET",
			data: {},
			timeout: 10000, // 10秒超时
			success: res => {
				try {
					// 检查是否是HTML错误页面
					if (typeof res.data === 'string' && res.data.includes('<!DOCTYPE html>')) {
						console.error('服务器返回了HTML错误页面，请确保服务器正常运行');
						reject(new Error('服务器未正常运行，请启动后端服务'));
						return;
					}
					
					if (res.statusCode === 200 && res.data && res.data.list) {
						const result = res.data.list.slice(0, 4);
						resolve(result);
					} else {
						console.error('接口返回格式错误:', res);
						reject(new Error('数据格式错误，请确保服务器正常运行'));
					}
				} catch (error) {
					console.error('数据处理错误:', error);
					reject(error);
				}
			},
			fail: (err) => {
				console.error('请求失败:', err);
				reject(new Error(`请求失败: ${err.errMsg || '未知错误'}`));
			}
		});
	});
}

export function playList() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/top/playlist`,
			method: "GET",
			data: {},
			timeout: 10000, // 10秒超时
			success: res => {
				try {
					// 检查是否是HTML错误页面
					if (typeof res.data === 'string' && res.data.includes('<!DOCTYPE html>')) {
						console.error('服务器返回了HTML错误页面，请确保服务器正常运行');
						reject(new Error('服务器未正常运行，请启动后端服务'));
						return;
					}
					
					if (res.statusCode === 200 && res.data && Array.isArray(res.data.playlists)) {
						const allPlaylists = res.data.playlists;
						const result = allPlaylists.slice(0, 5);
						resolve(result);
					} else {
						console.error('接口返回格式错误:', res);
						reject(new Error('数据格式错误，请确保服务器正常运行'));
					}
				} catch (error) {
					console.error('数据处理错误:', error);
					reject(error);
				}
			},
			fail: (err) => {
				console.error('请求失败:', err);
				reject(new Error(`请求失败: ${err.errMsg || '未知错误'}`));
			}
		});
	});
}

//最新专辑
export function latestAlbum() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/album/newest`,
			method: "GET",
			data: {},
			success: res => {
				const lists = res.data.albums || [];
				const listCount = lists.length;
				const result = [...lists]; // 复制原始数组

				// Fisher-Yates 洗牌算法（原地打乱数组）
				for (let i = listCount - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[result[i], result[j]] = [result[j], result[i]];
				}

				// 取前5条
				resolve(result.slice(0, 10));
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//热门歌手
export function popularSingers() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/top/artists`,
			method: "GET",
			data: {},
			success: res => {
				const lists = res.data.artists || [];
				const listCount = lists.length;
				const result = [...lists]; // 复制原始数组

				// Fisher-Yates 洗牌算法（原地打乱数组）
				for (let i = listCount - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[result[i], result[j]] = [result[j], result[i]];
				}

				// 取前5条
				resolve(result.slice(0, 10));
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//mv
export function allMv() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/mv/all`,
			method: "GET",
			data: {},
			success: res => {
				const lists = res.data.data || [];
				const listCount = lists.length;
				const result = [...lists]; // 复制原始数组

				// Fisher-Yates 洗牌算法（原地打乱数组）
				for (let i = listCount - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[result[i], result[j]] = [result[j], result[i]];
				}

				// 取前5条
				resolve(result.slice(0, 10));
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//推荐歌曲Recommend new music
export function recommendMusic() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/personalized/newsong`,
			method: "GET",
			data: {},
			success: res => {
				const lists = res.data.result || [];
				const listCount = lists.length;
				const result = [...lists]; // 复制原始数组

				// Fisher-Yates 洗牌算法（原地打乱数组）
				for (let i = listCount - 1; i > 0; i--) {
					const j = Math.floor(Math.random() * (i + 1));
					[result[i], result[j]] = [result[j], result[i]];
				}

				// 取前5条
				resolve(result.slice(0, 10));
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//搜索歌曲
export function searchMusic(keywords) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/search`,
			method: "GET",
			data: {
				keywords
			},
			success: res => {

				const lists = res.data.result.songs || [];
				const listCount = lists.length;
				// console.log(lists);
				const result = [...lists]; // 复制原始数组

				// // Fisher-Yates 洗牌算法（原地打乱数组）
				// for (let i = listCount - 1; i > 0; i--) {
				// 	const j = Math.floor(Math.random() * (i + 1));
				// 	[result[i], result[j]] = [result[j], result[i]];
				// }

				// 取前5条
				resolve(result.slice(0, 30));
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//游客登录
export function register() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/register/anonimous`,
			method: "GET",
			data: {},
			success: res => {
				// console.log(res.data.cookie);
				setCookie(res.data.cookie);
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//歌曲url查询
export function getSongUrl(id) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/song/url`,
			method: "GET",
			data: {
				id
			},
			// header: {
			// 	'Cookie': getCookie() // 从本地存储获取cookie并添加到请求头
			// },
			success: res => {
				resolve(res.data.data[0]);
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//歌词查询
export function getSongWordUrl(id) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/lyric`,
			method: "GET",
			data: {
				id
			},
			// header: {
			// 	'Cookie': getCookie() // 从本地存储获取cookie并添加到请求头
			// },
			success: res => {
				resolve(res.data.lrc.lyric);
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}
// http://localhost:3000/video/timeline/recommend
//视频id查询
export function getMVId() {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/video/timeline/recommend`,
			method: "GET",
			data: {},
			// header: {
			// 	'Cookie': getCookie() // 从本地存储获取cookie并添加到请求头
			// },
			success: res => {
				const randomItem = res.data.datas[Math.floor(Math.random() * res.data.datas.length)];
				// console.log('随机元素:', randomItem.data.vid);
				resolve(randomItem.data.vid);
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}

//视频url查询
export function getMVUrl(id) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${baseUrl}/video/url`,
			method: "GET",
			data: {
				id
			},
			// header: {
			// 	'Cookie': getCookie() // 从本地存储获取cookie并添加到请求头
			// },
			success: res => {
				resolve(res.data.urls[0].url);
			},
			fail: (err) => {
				console.log('请求失败', err); // 添加这行代码
				reject(err);
			},
			complete: () => {}
		});
	});
}